package com.zja.dao.Impl;

import com.zja.dao.ArticleViewHistoryDao;
import com.zja.dao.BaseDAO;
import com.zja.model.ArticleViewHistory;

import java.util.List;

/**
 * @author JA
 * @date: 2025/5/6
 * description:
 */
public class ArticleViewHistoryDaoImpl extends BaseDAO implements ArticleViewHistoryDao {
    @Override
    public List<ArticleViewHistory> selectViewRecordsOfMyArticles(Long authorId, int offset, int limit) {
        String sql ="SELECT h.*, a.title AS articleTitle " +
                "FROM article_view_history h " +
                "JOIN article a ON h.article_id = a.id " +
                "WHERE a.author_id = ? " +
                "ORDER BY h.view_time DESC " +
                "LIMIT ? OFFSET ?";
        try {
            return executeQuery(ArticleViewHistory.class, sql, authorId, limit, offset);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int countViewRecordsOfMyArticles(Long authorId) {
        String sql = "SELECT COUNT(*) FROM article_view_history h " +
                "JOIN article a ON h.article_id = a.id " +
                "WHERE a.author_id = ?";
        try {
            Number num = (Number) executeScalar(sql, authorId);
            return num.intValue();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean deleteViewRecordById(Long recordId, Long authorId) {
        String sql = "DELETE h FROM article_view_history h " +
                "JOIN article a ON h.article_id = a.id " +
                "WHERE h.id = ? AND a.author_id = ?";
        try {
            return executeUpdate(sql, recordId, authorId) ;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean deleteAllViewRecordsOfMyArticles(Long authorId) {
        String sql = "DELETE h FROM article_view_history h " +
                "JOIN article a ON h.article_id = a.id " +
                "WHERE a.author_id = ?";
        try {
            return executeUpdate(sql, authorId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
